import { useMemoizedFn } from 'ahooks'
import _ from 'lodash'

import { ICusAgGridProps } from '@/components/CusAgGrid'
import { IOrderListItem } from '../interface'
import { setColHideFlags } from './utils'

export const useOnColumnVisible = () => {
  return useMemoizedFn<NonNullable<ICusAgGridProps<IOrderListItem>['onColumnVisible']>>(e => {
    if ((e.source !== 'toolPanelUi' && e.source !== 'columnMenu') || !e.columns?.length) {
      return
    }

    const partialFlags: Record<string, boolean | undefined> = {}
    e.columns.forEach(col => {
      const field = col.getColDef().field
      if (field) {
        partialFlags[field] = !e.visible
      }
    })

    if (!_.isEmpty(partialFlags)) {
      setColHideFlags(partialFlags)
    }
  })
}
